<template>
  <div class="createPost-container">
    <sticky :className="'sub-navbar'" :z-index="$upZindex">


      <el-button v-has="'supplyInfoTable_add'" v-if="opt!='info'" v-loading="loading" style="margin-left: 10px;" type="success" @click="submitForm"  >{{$t('table.submit')}}
      </el-button>

      <el-button v-if="opt=='info'" v-loading="loading" style="margin-left: 10px;" type="success" @click="back">{{$t('table.back')}}
      </el-button>

    </sticky>

    <el-form class="form-container" :model="postForm" :rules="rules" ref="postForm" label-position="right" label-width="150px" style='width: 60%; margin-left:10px;margin-top:20px;'>
      <div class="divide-line">供应商信息</div>

      <el-form-item label="用户名" prop="username">
        {{postForm.username}}
      </el-form-item>
      <el-form-item label="简称" prop="abbreviation">
        {{postForm.abbreviation}}
      </el-form-item>
      <el-form-item label="机构类型" prop="organizationType">
        {{postForm.organizationType | $organizationTypeFilter}}
      </el-form-item>
      <el-form-item label="供应商类型" prop="supplyType">
        {{postForm.supplyType | $supplyTypeFilter}}
      </el-form-item>
      <el-form-item label="合作状态" prop="status">
        {{postForm.status | $supplyStatusFilter}}
      </el-form-item>
      <el-form-item label="评级" prop="supplyLevel">
        {{postForm.supplyLevel | $supplyLevelFilter}}
      </el-form-item>
      <el-form-item label="对接人" prop="personId">
        {{postForm.personName}}
      </el-form-item>
      <el-form-item label="入驻日期" prop="cooperationDate">
        <span v-if="postForm.cooperationDate">{{postForm.cooperationDate | $dateConvert}}</span>
      </el-form-item>

      <div class="divide-line">主体信息</div>


      <el-form-item label="官方名称" prop="officialName">
        {{postForm.officialName}}
      </el-form-item>

      <el-form-item label="Logo" prop="logo">
        <pan-thumb :image="postForm.logo"></pan-thumb>
        <el-button v-if="opt!='info'" type="primary" icon="upload" style="position: absolute;bottom: 15px;margin-left: 40px;" @click="imagecropperShow=true">更换Logo
        </el-button>
        <image-cropper :width="500" :height="500"
                       :url="uploadImgUrl"
                       @close='close'
                       @crop-upload-success="cropSuccess"
                       langType="zh"
                       :key="imagecropperKey"
                       v-show="imagecropperShow"
                       accept="image/*"
        ></image-cropper>
      </el-form-item>

      <el-form-item label="供应商地址" prop="address">
        {{postForm.address}}
      </el-form-item>

      <el-form-item label="背景特点" prop="background">
        {{postForm.background}}
      </el-form-item>




    
     	 <div style="width: 950px">
        <div class="divide-line">联系人信息</div>

        <el-table
          :data="postForm.supplyLinkMansDto"
          border
          fit highlight-current-row
          style="width: 100%;margin-left: 10px"
         >
          <el-table-column label="序号" type="index" width="50"></el-table-column>
          <el-table-column prop="linkName" label="姓名" width="100"></el-table-column>
          <el-table-column prop="linkMobile" label="电话" width="180"></el-table-column>
          <el-table-column prop="linkMail" label="邮箱" width="200"></el-table-column>
          <el-table-column prop="remark" label="备注" width="418"></el-table-column>
        </el-table>

      </div>

      <br>

    </el-form>


    <div v-if="opt=='info'">
      <div class="divide-line-long">合同信息</div>
      <SupplyContractList :supplyId="postForm.supplierId"></SupplyContractList>
    </div>

    <div v-if="opt=='info'">
      <div class="divide-line-long">沟通记录</div>
      <CommunicationList :supplyId="postForm.supplierId"></CommunicationList>
    </div>



    <div v-if="opt=='info'">
      <el-button v-has="'commTable_add'" v-loading="loading" type="success" style="margin-left: 400px;margin-bottom: 20px" @click="addCommunication" icon="el-icon-plus">新建沟通
      </el-button>
      <el-button v-has="'supplyContractTable_add'" v-loading="loading" type="success" style="margin-left: 50px;margin-bottom: 20px" @click="addContract" icon="el-icon-plus">新建合同
      </el-button>
      <el-button v-has="'supplyInfoTable_edit'" v-loading="loading" type="success" style="margin-left: 50px;margin-bottom: 20px" @click="editSupplyInfo">编辑供应商信息
      </el-button>

    </div>


  </div>

</template>

<script>
  // import Vue from 'vue'
  import Sticky from '@/components/Sticky' // 粘性header组件
  import {
    infoSupplyInfo,
    fetchLinkManList,
    createSupplyInfo,
    saveLinkMan,
    fetchSupplyLinkManList,
    delSupplyLinkMan
  } from '@/api/supply/supplyInfo'
  import ImageCropper from '@/components/ImageCropper'
  import PanThumb from '@/components/PanThumb'
  import SupplyContractList from '@/views/components/SupplyContractList.vue'
  import CommunicationList from '@/views/components/CommunicationList' // 水波纹指令
  const defaultForm = {
    code: ''
  }

  export default {
    name: 'supplyInfoAdd',
    components: { Sticky, ImageCropper, PanThumb, SupplyContractList, CommunicationList },
    data() {
      return {
        tableKey: 0,
        remnant: 200,
        imagecropperShow: false,
        imagecropperKey: 0,
        postForm: Object.assign({
          supplyLinkMansDto: [],
          background: ''

        }, defaultForm),
        loading: false,
        rules: {
          username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }, { min: 5, max: 16, message: '长度在5-16之间' }],
          abbreviation: [{ required: true, message: '简称不能为空', trigger: 'blur' }, { min: 5, max: 20, message: '长度在5-20之间' }],
          organizationType: [{ required: true, message: '请选择机构类型', trigger: 'change' }],
          supplyType: [{ required: true, message: '请选择供应商类型', trigger: 'change' }],
          status: [{ required: true, message: '请选择合作状态', trigger: 'change' }],
          supplyLevel: [{ required: true, message: '请选择供应商评级', trigger: 'change' }],
          personId: [{ required: true, message: '请选择对接人', trigger: 'change' }],
          // cooperationDate: [{ required: true, message: '请选择入驻日期', trigger: 'change' }],
          companyName: [{ required: true, message: '官方名称不能为空', trigger: 'blur' }, { min: 1, max: 30, message: '长度在1-30之间' }]
          // linkName: [{ required: true, message: '联系人不能为空', trigger: 'blur' }],
          // linkMobile: [{ required: true, message: '联系电话不能为空', trigger: 'blur' }]
        },
        listQuery: {
          supplyType: undefined,
          status: undefined,
          supplyLevel: undefined,
          organizationType: undefined
        },
        linkManOptions: [],
        linkManSaved: true,
        readonly: false,
        opt: this.$route.query.opt,
        linkManForm: {},
        uploadImgUrl: process.env.BASE_API + '/upload/doUploadFile.do'
      }
    },
    computed: {
      contentShortLength() {
        return this.postForm.content_short.length
      },
      textareaLength: function() {
        let leng = 0
        if (typeof this.postForm.background !== 'undefined' && this.postForm.background != null) {
          leng = this.postForm.background.length
        }
        return (200 - leng)
      }
    },
    created() {
      const supplierId = this.$route.query.supplierId
      const opt = this.$route.query.opt
      this.postForm.logo = 'https://wpimg.wallstcn.com/577965b9-bb9e-4e02-9f0c-095b41417191'
      this.postForm.supplierId = supplierId
      if (supplierId != null) {
        infoSupplyInfo(supplierId).then(response => {
          if (response.success) {
            this.postForm = Object.assign(this.postForm, response.content) // copy obj
            if (!this.postForm.logo) {
              this.postForm.logo = 'https://wpimg.wallstcn.com/577965b9-bb9e-4e02-9f0c-095b41417191'
            }
            this.buildLinkManForm()
          } else {
            this.$message({
              type: 'fail',
              message: response.message
            })
            this.$router.go(-1)
          }
        })
        if (opt === 'info') {
          this.readonly = true
        }
      }
      this.getLinkManList()
    },

    methods: {
      buildLinkManForm: function() {
        // 供应商联系人
        var params = { supplyId: this.postForm.supplierId }
        console.info(params)

        fetchSupplyLinkManList(params).then(response => {
          this.postForm.supplyLinkMansDto = Object.assign([], response.content) // copy obj
        })
      },
      saveLinkMan: function() {
        // 添加之前确保供应商信息已经保存
        if (!this.saveSupplyInfo4linkMan()) {
          return
        }
        // 添加or更新
        this.$refs['linkManForm'].validate((valid) => {
          if (valid) {
            this.linkManForm = Object.assign(this.linkManForm, { supplyId: this.postForm.id })
            saveLinkMan(this.linkManForm).then((response) => {
              if (response.success) {
                this.$notify({
                  message: '联系人保存成功',
                  type: 'success',
                  duration: 2000
                })
                // 重新拉取
                this.buildLinkManForm()

                // 清空
                this.linkManForm = {}
              } else {
                this.$notify({
                  message: '联系人保存失败',
                  type: 'fail',
                  duration: 2000
                })
              }
            })
          }
        })
      },
      editLinkMan(data) {
        this.linkManForm = data
      },
      cleanForm() {
        this.linkManForm = {}
      },
      delLinkMan(delId, index) {
        this.$confirm('此操作将永久删除该联系人, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then((response) => {
          // 调用删除接口
          delSupplyLinkMan({ supplyLinkManId: delId }).then(response => {
            if (response.success) {
              this.$notify({
                message: '联系人删除成功',
                type: 'success',
                duration: 2000
              })
              this.buildLinkManForm()
            } else {
              this.$notify({
                message: '联系人删除失败',
                type: 'fail',
                duration: 2000
              })
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      cropSuccess(resData) {
        this.imagecropperShow = false
        this.imagecropperKey = this.imagecropperKey + 1
        this.postForm.logo = resData
      },
      close() {
        this.imagecropperShow = false
      },
      getLinkManList() {
        this.listLoading = true
        fetchLinkManList().then(response => {
          if (response.success) {
            for (var a = 0; a < response.content.length; a++) {
              var aa = { label: response.content[a].userName, key: response.content[a].id }
              this.linkManOptions.push(aa)
            }
          }
        })
      },
      submitForm() {
        this.$refs['postForm'].validate((valid) => {
          if (valid) {
            this.postForm.supplyLinkMans = null
            createSupplyInfo(this.postForm).then((response) => {
              if (response.success) {
                this.$notify({
                  message: '提交成功',
                  type: 'success',
                  duration: 2000
                })
                this.$router.push({ name: 'supplyInfoTable' })
              } else {
                this.$notify({
                  message: '提交失败',
                  type: 'fail',
                  duration: 2000
                })
              }
            })
          }
        })
      },
      addCommunication() {
        this.$router.push({ name: 'commAdd', query: { supplyId: this.postForm.supplierId, supplyName: this.postForm.abbreviation }})
      },
      addContract() {
        this.$router.push({ name: 'supplyContractAdd', query: { supplyId: this.postForm.supplierId, supplyName: this.postForm.abbreviation }})
      },
      editSupplyInfo() {
        this.$router.push({ name: 'supplyInfoEdit', query: { supplierId: this.postForm.supplierId }})
      },
      back() {
        // this.$router.push({ name: 'supplyInfoTable' })
        history.go(-1)
      }

    },
    watch: {
      '$route'(to, from) {
        if (from.name === 'supplyInfo') {
          this.$router.go(0)
        }
      }
    }
  }
</script>

<style scoped>
  .avatar{
    width: 200px;
    height: 200px;
    border-radius: 50%;
  }


/*.el-table--border td{
	border-right: none;
}*/
</style>
